package com.lzs.bootsafety.common.util.aop;

import com.alibaba.fastjson.JSON;
import com.lzs.bootsafety.business.logs.entity.SysExc;
import com.lzs.bootsafety.business.logs.entity.SysOperLogs;
import com.lzs.bootsafety.business.logs.entity.SysVisit;
import com.lzs.bootsafety.business.logs.service.SysExcService;
import com.lzs.bootsafety.business.logs.service.SysOperLogsService;
import com.lzs.bootsafety.business.logs.service.SysVisitService;
import com.lzs.bootsafety.business.sys.entity.SysUser;
import com.lzs.bootsafety.common.util.annotation.OperLog;
import com.lzs.bootsafety.common.util.http.AddressUtil;
import com.lzs.bootsafety.common.util.http.IpUtils;
import com.lzs.bootsafety.common.util.http.LocationByIP;
import org.apache.shiro.SecurityUtils;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.AfterThrowing;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.aspectj.lang.reflect.MethodSignature;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Aspect
@Component
public class OperLogAspect {
    private static final Logger logger = LoggerFactory.getLogger(OperLogAspect.class);
    @Autowired
    private SysOperLogsService sysOperLogsService;
    @Autowired
    private SysExcService sysExcService;
    @Autowired
    private SysVisitService sysVisitService;
    @Autowired
    /**
     * 日志切入点 在注解的位置切入代码
     */
    @Pointcut("@annotation(com.lzs.bootsafety.common.util.annotation.OperLog)")
    public void operLogPoinCut() {
    }

    /**
     * 异常切入点，记录异常操作日志，
     */
    @Pointcut("execution(* com.lzs.bootsafety..*.*(..))")
    public void operExceptionLogPoinCut() {

    }

    /**
     * 正常返回通知，拦截用户操作日志，请求执行完成后执行，如果抛出异常则不会执行
     *
     * @param joinPoint
     * @param keys
     */
    @AfterReturning(value = "operLogPoinCut()", returning = "keys")
    public void saveOperLogs(JoinPoint joinPoint, Object keys) {
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        SysOperLogs log = new SysOperLogs();
        SysVisit visit = new SysVisit();
        try {
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            //获取切入点所在的方法
            Method method = signature.getMethod();
            OperLog operlog = method.getAnnotation(OperLog.class);
            if (operlog != null) {
                String operModule = operlog.operModule();
                String operType = String.valueOf(operlog.operType().getLabel()) ;
                log.setOperModule(operModule);
                log.setOperType(operType);
            }
            //获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            //请求方法名
            String methodName = method.getName();
            //请求方法
            methodName = className + "." + methodName;
            log.setOperMethod(methodName);
            //请求参数
            Map<String, String> map = converMap(request.getParameterMap());
            //将参数数组转为json
            String params = JSON.toJSONString(map);
            if (operlog.isSaveReqParams()) {
                log.setOperReqPara(params);
            } else if (operlog.isSaveResParams()) {
                log.setOperRespPara(JSON.toJSONString(keys));
            }
            //操作人
            SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
            log.setOperUsername(user.getUsername());
            log.setOperIp(IpUtils.getIpAddr(request));
            log.setOperDept(user.getDept().getName());
            //请求的url
            log.setOperUrl(request.getRequestURI());
            log.setOperBrower(AddressUtil.getBrowserName(request));
            log.setOperTime(new Date());
            log.setOperOs(AddressUtil.getOsName(request));
            //查询次数有限制
            log.setOperAddress(LocationByIP.request(IpUtils.getIpAddr(request)));
            if (operlog.isLogin()){//登录日志
                visit.setVisitTime(new Date());
                visit.setVisitAddr(LocationByIP.request(IpUtils.getIpAddr(request)));//基于百度IP定位
                visit.setVisitBrowser(AddressUtil.getBrowserName(request));
                visit.setVisitOs(AddressUtil.getOsName(request));
                visit.setVisitIp(IpUtils.getIpAddr(request));
                visit.setVisitName(user.getUsername());
                sysVisitService.insertSelective(visit);
            }
            sysOperLogsService.insertSelective(log);
        }catch (Exception e){
            e.printStackTrace();
        }
    }

    /**
     * request参数转换
     */
    public Map<String, String> converMap(Map<String, String[]> paraMap) {
        Map<String, String> map = new HashMap<String, String>();
        for (String key : paraMap.keySet()) {
            map.put(key, paraMap.get(key)[0]);
        }
        return map;
    }

    /**
     * 异常返回通知，用于拦截异常日志信息 连接点抛出异常后执行
     * @param joinPoint 切入点
     * @param e         异常信息
     */
    @AfterThrowing(pointcut = "operExceptionLogPoinCut()", throwing = "e")
    public void saveExceptionLog(JoinPoint joinPoint, Throwable e) {
        // 获取RequestAttributes
        RequestAttributes requestAttributes = RequestContextHolder.getRequestAttributes();
        // 从获取RequestAttributes中获取HttpServletRequest的信息
        HttpServletRequest request = (HttpServletRequest) requestAttributes.resolveReference(RequestAttributes.REFERENCE_REQUEST);
        SysExc excLog = new SysExc();
        try {
            // 从切面织入点处通过反射机制获取织入点处的方法
            MethodSignature signature = (MethodSignature) joinPoint.getSignature();
            // 获取切入点所在的方法
            Method method = signature.getMethod();
            // 获取请求的类名
            String className = joinPoint.getTarget().getClass().getName();
            // 获取请求的方法名
            String methodName = method.getName();
            methodName = className + "." + methodName;
            // 请求的参数
            Map<String, String> rtnMap = converMap(request.getParameterMap());
            // 将参数所在的数组转换成json
            String params = JSON.toJSONString(rtnMap);
            // 请求参数
            excLog.setExcReqPara(params);
            // 请求方法名
            excLog.setOperMethod(methodName);
            // 异常名称
            excLog.setExcName(e.getClass().getName());
            // 异常信息
            excLog.setExcMsg(stackTraceToString(e.getClass().getName(), e.getMessage(), e.getStackTrace()));
            // 操作员ID
            SysUser user = (SysUser) SecurityUtils.getSubject().getPrincipal();
            excLog.setOperUserId(user.getUserId());
            // 操作员名称
            excLog.setOperUserName(user.getUsername());
            // 操作URI
            excLog.setOperUrl(request.getRequestURI());
            // 操作员IP
            excLog.setOperIp(IpUtils.getIpAddr(request));
            // 发生异常时间
            excLog.setOperCreateTime(new Date());
            //操作系统
            excLog.setOperOs(AddressUtil.getOsName(request));
            //浏览器
            excLog.setOperBrowser(AddressUtil.getBrowserName(request));
            sysExcService.addSelective(excLog);
        } catch (Exception e2) {
            e2.printStackTrace();
        }

    }

    /**
     * 转换异常信息为字符串
     * @param exceptionName    异常名称
     * @param exceptionMessage 异常信息
     * @param elements         堆栈信息
     */
    public String stackTraceToString(String exceptionName, String exceptionMessage, StackTraceElement[] elements) {
        StringBuffer strbuff = new StringBuffer();
        for (StackTraceElement stet : elements) {
            strbuff.append(stet + "\n");
        }
        String message = exceptionName + ":" + exceptionMessage + "\n\t" + strbuff.toString();
        return message;
    }
}
